package com.xujl.mvcbind.widget.list;

import android.view.View;

import java.util.ArrayList;
import java.util.List;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

public abstract class AbsFragmentAdapter<T> {
    private List<T> mDataList;
    private FragmentManager mFragmentManager;
    private List<Fragment> mFragmentList = new ArrayList<>();

    public AbsFragmentAdapter (List<T> dataList, FragmentManager fragmentManager) {
        mDataList = dataList;
        mFragmentManager = fragmentManager;
    }

    public abstract Fragment createFragment (int position);

    public abstract View createFragmentView (View root, int position);


    public List<T> getDataList () {
        return mDataList;
    }

    public void setDataList (List<T> dataList) {
        mDataList = dataList;
    }

    void createLayout (ListFragmentLayout listFragmentLayout) {
        mFragmentList.clear();
        listFragmentLayout.mRootLL.removeAllViews();
        final FragmentTransaction transaction = mFragmentManager.beginTransaction();
        for (int i = 0; i < mDataList.size(); i++) {
            final View view = createFragmentView(listFragmentLayout.mRootLL, i);
            view.setId(View.generateViewId());
            listFragmentLayout.mRootLL.addView(view);
            final Fragment fragment = createFragment(i);
            mFragmentList.add(fragment);
            transaction.replace(view.getId(), fragment);
        }
        transaction.commit();
    }
}
